var util = require('../../utils/util.js')
var app = getApp()
const audio = require('../../utils/audio.js')
const plugin = requirePlugin("WechatSI")
const manager = plugin.getRecordRecognitionManager()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    level: ["/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
    ],
    levelFont: "",
    hide: false,
    contentLength: 0,
    accounts: [],
    accountIndex: -1,
    files: [],
    imgUrl: [],
    address: "",
    loading: 1,
    videoSrc:"",
    video:"",
    cavasList:[{
      id:0,
      imageWidth:0,
      imageHeight:0
    }],
    mydata:"",
    isDelelte: 0, 
    isSupervising: false,
    isSupervsor: false,
    superviseSchoolId: 0,
    audioOn: false,
    speakOn: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      altitude: true,
      fail: (res) => {
        //不允许打开定位
        wx.hideLoading()
        wx.getSetting({
          success(res) {
            //开启小程序内定位
            if (res.authSetting["scope.userLocation"] == false) {
              wx.showModal({
                content: '请允许小程序使用地理位置功能！您可以在【我的】页面点击【设置】按钮快捷设置。',
                confirmText: "去设置",
                success: res => {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/mine/mine'
                    })
                  }
                }
              })
            } else {
              //开启系统设置定位
              wx.getSystemInfo({
                success: res => {
                  console.log(res)
                  if (res.platform == "ios") {
                    that.setData({
                      locationContent: "请在系统设置-微信里开启允许微信使用地理位置的开关"
                    })
                  }
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                },
                fail: res => {
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                }
              })
            }

          }
        })
      },
      success: res => {
        console.log(res)
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          altitude: res.altitude
        })
      }
    })
    if(app.globalData.isSupervising == true){
      this.setData({
        isSupervsor: true,
        isSupervising: app.globalData.isSupervising,
        address: app.globalData.superviseSchoolName,
        superviseSchoolId: app.globalData.superviseSchoolId
      })
    }
    if(app.globalData.isSuddenSupervising == true){
      this.setData({
        isSupervsor: true,
        isSuddenSupervising: app.globalData.isSuddenSupervising,
        address: app.globalData.suddensuperviseSchoolName,
        superviseSchoolId: app.globalData.suddensuperviseSchoolId
      })
    }
    
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getAllValidInspectItems',
      method: 'POST',
      data: {
        schoolId: app.globalData.departmentId
      },
      dataType: 'json',
      success: res => {
        let accounts = [],
          categoryId = []
        for (let i = 0; i < res.data.length; i++) {
          accounts.push({
            item: res.data[i].category,
            checked: false,
            realname: res.data[i].realname
          })
          categoryId.push(res.data[i].categoryId)
        }
        this.setData({
          accounts: accounts,
          categoryId: categoryId
        })
        if (options.id != null) {

          this.setData({
            accountIndex: options.id - 1
          })
        }
      },
      fail: res => {
        wx.showToast({
          title: '网络异常！',
          image: '/images/warning.png'
        })
      },
      complete: () => {
        this.setData({
          loading: 0
        })
      }
    })
    //清楚照片缓存
    wx.removeStorage({
      key: 'fileAndImg'
    })
    audio.initRecord(manager,this,/^\u5728(\S+)\u53D1\u73B0(\S+)$/g)
  },
  onShow:function(e){
    this.setData({
      files: this.data.files,
      imgUrl: this.data.imgUrl
    })
  },
  onUnload:function(e){
    if(this.data.isDelelte == 0){
      for(let i = 0 ; i < this.data.imgUrl.length; i++){
        let target = this.data.imgUrl[i] 
        wx.request({
          url: app.inspectUrl + '/WeChat/weChatSystem/deleteFile',
          method: 'POST',
          data: {
            filename: target.split("image/")[1]
          },
          dataType: 'json',
          success: res => {
            console.log("删除成功")
          }
        })
      }
    }
  },

  getAddress: function(e) {
    this.setData({
      address: e.detail.value
    })
  },

  clickLevel: function(e) {
    let clickId = parseInt(e.target.id)
    let tempLevel = []
    let tempLevelFont
    for (let i = 0; i < 5; i++) {
      if (i <= clickId) {
        tempLevel.push("/images/star_fill.png")
      } else {
        tempLevel.push("/images/star.png")
      }
    }
    switch (clickId) {
      case 0:
        tempLevelFont = "一般"
        break
      case 1:
        tempLevelFont = "安全"
        break
      case 2:
        tempLevelFont = "一般"
        break
      case 3:
        tempLevelFont = "危险"
        break
      case 4:
        tempLevelFont = "非常危险"
        break
    }
    this.setData({
      level: tempLevel,
      levelFont: tempLevelFont
    })
  },
  //自定义相机组件
  toCamera:function(e){
    console.log("ss", this.data.contentLength);
    let category 
    let waringInfo = ""
    if (this.data.accountIndex == -1) {
      waringInfo = "请选择隐患类型"
    } else if (this.data.address == "") {
      waringInfo = "请输入隐患地点"
    } else if (this.data.levelFont == "") {
      waringInfo = "请选择隐患等级"
    } else if (this.data.recordContent == "" || !this.data.recordContent) {
      waringInfo = "请输入详细问题"
    }else if(this.data.contentLength<5){
      waringInfo = "描述不少于五字"
    }
    if (waringInfo != "") {
      wx.showToast({
        title: waringInfo,
        image: "/images/warning.png"
      })
    }else{
      if(this.data.selectedIndex == undefined || this.data.selectedIndex == null){
        category = ''
      }else{
        category = this.data.accounts[this.data.selectedIndex].item
      }
      if(this.data.recordContent == undefined){
         this.setData({
           recordContent:''
         })
      }
      wx.navigateTo({
        url: '../../subpages/pages/cameraIdentified/cameraIdentified?address='+this.data.address+'&recordContent='
        +this.data.recordContent+'&type=1'+'&level='+this.data.levelFont+'&category='+category
      })
    }
  },
  //原生相机
  chooseImage: function(e) {
    var that = this;
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showLoading({
          title: "图片上传中",
          mask: true
        })
        let tempImg = res.tempFilePaths
        console.log("tempImg",tempImg)
        let cavasList = []
        for(let i=0;i<res.tempFilePaths.length;i++){
          cavasList.push({
            id : i ,
            imageWidth : 0 ,
            imageHeight : 0
          })
        }
        console.log("cavasList",cavasList)
        that.setData({
          cavasList : cavasList,
        })
        //新增图片水印
        let datetime = util.formatTime(new Date());
        for(let i=0;i<res.tempFilePaths.length;i++){
          wx.getImageInfo({
            src: tempImg[i],
            success:function(res2){
              var width = res2.width 
              var height = res2.height
              console.log("width",width)
              console.log("height",height)
              //获取屏幕宽度
              let screenWidth = wx.getSystemInfoSync().windowWidth
              console.log("screenWidth",screenWidth)
              //处理一下图片的宽高的比例
              let ratio = width/height
              width = screenWidth
              height = width/ratio
              that.data.cavasList[i].imageWidth = width
              that.data.cavasList[i].imageHeight = height
              that.setData({
                cavasList: cavasList
              })
              var ctx = wx.createCanvasContext('myCanvas' + i)
              ctx.drawImage(res2.path,0,0,width,height)
              for (let j = 1; j < 2; j++) {
                  ctx.beginPath()
                  ctx.setFontSize(16)
                  ctx.setFillStyle('#B7CFF3')
                  ctx.setTextAlign("left")
                  ctx.fillText('时间：'+datetime, 15, (height-95))
                  ctx.fillText('地点：'+that.data.address, 15, (height-70) * j)
                  ctx.fillText('描述：'+that.data.recordContent, 15, (height-45) * j)
                  ctx.fillText('上报人：'+app.globalData.realname, 15, (height-20) * j)
              }
              ctx.draw()
              setTimeout(function(){
                wx.canvasToTempFilePath({
                    canvasId: 'myCanvas'+i,
                    success: function (res3) {
                        var tempFilePath = res3.tempFilePath;
                        //图片上传功能
                        wx.uploadFile({
                          url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload',
                          // filePath: res.tempFilePaths[i],
                          filePath: tempFilePath,
                          name: 'file',
                          header: {
                            "Content-Type": "multipart/form-data"
                          },
                          success: res4 => {
                            console.log(1)
                            console.log("res4",res4.data)
                            if (res.statusCode == 500) {
                              wx.showToast({
                                title: "图片上传失败",
                                image: "/images/error.png"
                              })
                            } else{
                              wx.showToast({
                                title: "上传成功"
                              })
                              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                              that.setData({
                                files: that.data.files.concat(tempFilePath)
                              })
                              if (that.data.files.length == 3) {
                                that.setData({
                                  hide: true
                                })
                              }
                              that.data.imgUrl.push(res4.data)
                            }
                          },
                          fail: res4 => {
                            console.log(2)
                            console.log(res4)
                            wx.showToast({
                              title: "图片上传失败",
                              image: "/images/error.png"
                            })
                          }
                        })
                    },
                    fail: function (res3) {
                        console.log(res3);
                    }
                });
               },500);
            }
          })
        }
      }
    })

  },

  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  inputContent: function(e) {
    e.detail.value = app.trim(e.detail.value)
    this.setData({
      recordContent: e.detail.value,
      contentLength: parseInt(e.detail.value.length)
    })
  },

  bindAccountChange: function(e) {
    this.setData({
      accountIndex: e.detail.value
    })
  },

  formSubmit: util.throttle(function(e) {
    let schoolId
    let inspectConditionId
    let superviseId
    let suddenSuperviseId 
    if(app.globalData.isSupervising == true){
      schoolId = app.globalData.superviseSchoolId
      inspectConditionId = -1
      superviseId = -app.globalData.superviseId
    }else if(app.globalData.isSuddenSupervising == true){
      schoolId = app.globalData.suddensuperviseSchoolId
      inspectConditionId = -1
      suddenSuperviseId = app.globalData.suddensuperviseId
    }else{
      schoolId = app.globalData.departmentId
      inspectConditionId = 0
    }
    console.log("提交了");
    this.setData({
      isDelelte : 1 
    })
    let waringInfo = ""
    if (this.data.accountIndex == -1) {
      waringInfo = "请选择隐患类型"
    } else if (e.detail.value.address == "") {
      waringInfo = "请输入隐患地点"
    } else if (this.data.levelFont == "") {
      waringInfo = "请选择隐患等级"
    } else if (this.data.recordContent == "" || !this.data.recordContent) {
      waringInfo = "请输入详细问题"
    } else if(this.data.imgUrl.length == 0 && this.data.video == "") {
      waringInfo = "请附上照片或视频"
    } else {
      let level = 0
      switch (this.data.levelFont) {
        case "安全":
          level = 1
          break
        case "一般":
          level = 2
          break
        case "危险":
          level = 3
          break
        case "非常危险":
          level = 4
          break
      }
      let photo = ""
      for (let j = 0; j < this.data.imgUrl.length; j++) {
        photo += this.data.imgUrl[j]
        if (j != this.data.imgUrl.length - 1) {
           photo += ","
        }
      }
     
      wx.showLoading({
        title: '正在提交'
      })
      wx.request({
        url: app.inspectUrl + '/WeChat/weChatSystem/safetyReport',
        method: 'POST',
        data: {
          schoolId: schoolId,
          safetyLevel: level,
          categoryId: this.data.categoryId[this.data.accountIndex],
          address: e.detail.value.address,
          content: this.data.recordContent,
          photo: photo,
          reporter: app.globalData.userId,
          video:this.data.video,
          inspectConditionId: inspectConditionId,
          superviseId: superviseId,
          suddenSuperviseId: suddenSuperviseId,
          latitude: this.data.latitude,
          longitude: this.data.longitude,
          altitude: this.data.altitude
        },
        dataType: 'json',
        success: res => {
          if (res.data.res == "success") {
            let safetySceneId = res.data.data
            wx.showLoading({
              title: '推送异常信息',
              mask: true
            })
            // 推送
            wx.request({
              url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
              method: 'GET',
              dataType: 'json',
              success: res => {
                let access_token = res.data.access_token
                wx.request({
                  url: app.inspectUrl + '/WeChat/weChatSystem/getChargeManWeChatId',
                  method: 'POST',
                  data: {
                    // safetySceneId:safetySceneId, 隐患提交后，通过这个接口插入查找出来的推送人 userPush
                    categoryId: this.data.categoryId[this.data.accountIndex],
                    address: e.detail.value.address,
                    schoolId: this.data.isSupervsor == true ? this.data.superviseSchoolId : app.globalData.departmentId
                  },
                  dataType: 'json',
                  success: res => {
                    console.log("res",res);
                    
                    let unbind = []
                    for (let i = 0; i < res.data.length; i++) {
                      if (res.data[i].res == "success") {
                        let datetime = util.formatTime(new Date());
                        console.log("this is touser!!!!!!");
                        console.log(res.data[i].msg);
                        wx.request({
                          url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                          data: {
                            template: 1,
                            accessToken: access_token,
                            touser: res.data[i].msg,
                            // touser: 'oq0rl1DdHVhyd1ogmBotj-2GEN2g',
                            safetySceneId: safetySceneId,
                            miniprogram: {
                              appid: 'wxfb5354f928ccc68e',
                              pagepath: 'pages/indexBlank/indexBlank'
                            }, 
                            data: {
                              first: {
                                value: "安全隐患"
                              },
                              keyword1: {
                                value: app.globalData.realname
                              },
                              keyword2: {
                                value: datetime
                              },
                              keyword3: {
                                value: `在${e.detail.value.address}发现${this.data.accounts[this.data.accountIndex].item}类型隐患，请及时查看！`
                              }
                            }
                          },
                          method: 'POST',
                          dataType: 'json'
                        })
                      } else {
                        //获取所有未绑定主管姓名
                        unbind.push(res.data[i].msg)
                      }
                    }
                    //提示未绑定信息
                    if (unbind.length != 0) {
                      let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                      wx.showModal({
                        title: "提示",
                        showCancel: false,
                        content: msg,
                      })
                    }
                  }
                })
              }
            })
            wx.reLaunch({
              url: '/pages/safetysence/safetysence'
            })
            wx.removeStorage({
              key: 'fileAndImg'
            })
          } else {
            wx.showToast({
              title: '上报失败',
              image: "/images/error.png"
            })
          }
        },
        fail: () => {
          wx.showToast({
            title: '网络异常！',
            mask: true,
            image: "/images/error.png"
          })
        }
      })
    }
    if (waringInfo != "") {
      wx.showToast({
        title: waringInfo,
        icon: 'none'
        // image: "/images/warning.png"
      })
    }
  }),

  deleteImage: function(e) {
    let targetIndex = e.currentTarget.dataset.index
    let target = this.data.imgUrl[targetIndex]
    let temp = []
    let tempUrl = []
    let filesLength = this.data.files.length
    for (let i = 0; i < this.data.files.length; i++) {
      if (i != targetIndex) {
        temp.push(this.data.files[i])
        tempUrl.push(this.data.imgUrl[i])
      }
    }

    wx.showActionSheet({
      itemList: ['删除这张照片'],
      success: res => {
        if (!res.cancel) {
          this.setData({
            files: temp,
            imgUrl: tempUrl
          })
          wx.setStorageSync('fileAndImg', {
            files : this.data.files,
            imgUrl : this.data.imgUrl
          })
          console.log("fileAndImg2",wx.getStorageSync('fileAndImg'))
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteFile',
            method: 'POST',
            data: {
              filename: target.split("image/")[1]
            },
            dataType: 'json',
            success: res => {
              if (filesLength == 3) {
                this.setData({
                  hide: false
                })
              }
            }
          })
        }
      }
    })
  },

  showModal(e) {
    console.log("是我呀",e)
    let accounts = this.data.accounts.map((item, index) => {
      return {
        item: item.item,
        checked: index == this.data.accountIndex ? true : false,
        realname: item.realname
      }
    })
    this.setData({
      modalName: "RadioModal",
      accounts: accounts,
      modalComfirm: this.data.selectedIndex != null ? true : false,
      // forwardId: e.currentTarget.dataset.id
    })
  },

  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  radioSelect(e) {
    console.log(e)
    let radioIndex = e.currentTarget.dataset.index,
      accounts = this.data.accounts.map((item, index) => {
        return {
          item: item.item,
          checked: index == radioIndex ? true : false,
          realname: item.realname
        }
      }),
      status
    this.setData({
      accounts: accounts,
      selectedIndex: radioIndex
    })
    if (this.data.selectedIndex != null) status = true
    else status = false
    this.setData({
      modalComfirm: status
    })
  },

  confirmSelect(e) {
    this.setData({
      accountIndex: this.data.selectedIndex,
      modalName: null
    })
  },

  //新增视频录制功能
  press:function (e) {
    wx.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      camera: 'back',
      success: res => {
        if(res.size > 2097152){
          wx.showToast({
            title: '文件大于2M！',
            mask: true,
            image: "/images/error.png"
          })
        }else{
          wx.uploadFile({
            url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload2',
            filePath: res.tempFilePath,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success:res=>{
              console.log(res.data)
              this.setData({
                videoSrc: app.imageUrl+res.data,
                video: res.data
              })
            }
          })
        }
      },
      fail(res){
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo:function(e) {
    let target = this.data.video
    wx.showActionSheet({
      itemList: ['删除视频'],
      success: res => {
        if (!res.cancel) {
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteVideo',
            method: 'POST',
            data: {
              filename: target.split("video/")[1]
            },
            dataType: 'json',
            success: res => {
              if(res.data == "success"){
                this.setData({
                  video : ""
                })
              }
            }
          })
        }
      }
    })
  },

  startSpeak: function() {
    this.setData({
      audioOn: true
    })
  },

  cancelAudio: function() {
    // this.setData({
    //   audioOn: false,
    //   speakOn: false
    // })
    audio.endStreamRecord(manager,this)
  },

  streamRecord: function() {
    audio.streamRecord(manager,this)
  },
  endStreamRecord: function() {
    audio.endStreamRecord(manager,this)
  }
})